<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Device\Service;

use App\Http\CurrentUser;
use App\Service\IService;
use Plugin\Device\Model\RdDeviceRod;
use Plugin\Device\Repository\RdDeviceBroadcastRepository;
use Plugin\Device\Repository\RdDeviceRodRepository;
use Plugin\Device\Repository\RdDeviceSerialRepository;
use Plugin\Organization\Model\RdOrganizeArea;
use Plugin\Organization\Model\RdOrganizeAreaStand;
use Plugin\Organization\Model\RdOrganizeProjLine;
use Plugin\Organization\Model\RdOrganizeZone;
use Plugin\Organization\Repository\RdOrganizeUserStandRepository;

/**
 * 装置组服务类
 */
final class RdDeviceRodService extends IService
{
    public function __construct(
        protected readonly RdDeviceRodRepository         $repository,
        protected readonly RdOrganizeUserStandRepository $userStandRepository,
        protected CurrentUser                            $currentUser,
        protected readonly RdDeviceBroadcastRepository   $broadcastRepository,
        protected readonly RdDeviceSerialRepository      $serialRepository,
    )
    {
    }

    public function tree()
    {
        $ownStands = $this->userStandRepository->getQuery()
            ->where('status', 1)
            ->where('user_id', $this->currentUser->id())
            ->pluck('stand_id')
            ->toArray();
        if (empty($ownStands)) {
            return [];
        }

        // 获取所有大区
        $zones = RdOrganizeZone::query()->where('status', 1)->get(['id', 'name']);

        $tree = [];

        foreach ($zones as $zone) {
            $zoneData = [
                'id' => $zone->id,
                'name' => $zone->name,
                'type' => 'zone',
                'children' => []
            ];

            // 获取项目（项目线）
            $projLines = RdOrganizeProjLine::query()
                ->where('zone_id', $zone->id)
                ->where('status', 1)
                ->get(['id', 'name']);

            foreach ($projLines as $projLine) {
                $projLineData = [
                    'id' => $projLine->id,
                    'name' => $projLine->name,
                    'type' => 'proj_line',
                    'children' => []
                ];

                // 获取工区
                $areas = RdOrganizeArea::query()
                    ->where('proj_line_id', $projLine->id)
                    ->where('status', 1)
                    ->get(['id', 'name']);

                foreach ($areas as $area) {
                    $areaData = [
                        'id' => $area->id,
                        'name' => $area->name,
                        'type' => 'area',
                        'children' => []
                    ];

                    // 获取站点
                    $stands = RdOrganizeAreaStand::query()
                        ->where('area_id', $area->id)
                        ->get(['id', 'name']);
                    foreach ($stands as $stand) {
                        if (!in_array($stand->id, $ownStands)) {
                            continue;
                        }
                        $standData = [
                            'id' => $stand->id,
                            'name' => $stand->name,
                            'type' => 'stand',
                            'children' => []
                        ];

                        // 获取设备组
                        $rods = RdDeviceRod::query()
                            ->where('stand_id', $stand->id)
                            ->get(['id', 'name']);

                        foreach ($rods as $rod) {
                            $rodData = [
                                'id' => $rod->id,
                                'name' => $rod->name,
                                'type' => 'rod',
                                'broadcast' => $this->broadcastRepository->getQuery()
                                    ->where('rod_id', $rod->id)
                                    ->get(['id', 'code', 'name', 'server_id', 'device_id', 'status', 'addr'])
                                    ->toArray(),
                                'camera' => $this->serialRepository->getQuery()
                                    ->where('rod_id', $rod->id)
                                    ->get(['id', 'name', 'device_serial', 'channel_no', 'type', 'online', 'addr'])
                                    ->toArray(),
                            ];

                            $standData['children'][] = $rodData;
                        }
                        if (empty($standData['children'])) {
                            continue;
                        }
                        $areaData['children'][] = $standData;
                    }
                    if (empty($areaData['children'])) {
                        continue;
                    }
                    $projLineData['children'][] = $areaData;
                }
                if (empty($projLineData['children'])) {
                    continue;
                }
                $zoneData['children'][] = $projLineData;
            }
            if (empty($zoneData['children'])) {
                continue;
            }
            $tree[] = $zoneData;
        }

        return $tree;
    }
}